package concurrencyPractice.chapter04;

import concurrencyPractice.NotThreadSafe;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 程序4-10 NumberRange不足以保护它的不可变条件
 * @date 2023/12/28 17:04:05
 */
@NotThreadSafe
public class NumberRange {
    // 不变性条件lower < upper
    private final AtomicInteger lower = new AtomicInteger();
    private final AtomicInteger upper = new AtomicInteger();

    public void setLower(int i) {
        // 不安全的先检查后执行
        if (i > upper.get()) {
            throw new IllegalArgumentException("can't set lower " + i + " > upper");
        }
        lower.set(i);
    }

    public void setUpper(int i) {
        // 不安全的先检查后执行
        if (i < lower.get()) {
            throw new IllegalArgumentException("can't set upper " + i + " < lower");
        }
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return i >= lower.get() && i <= upper.get();
    }
}
